import {
  defineComponent,
  ref,
} from 'vue'

import {
  ElButton,
  ElCol,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElOption,
  ElRow,
  ElSelect,
} from 'element-plus'
import { useRouter } from 'vue-router'
import DictTag from '@/components/DictTag/index.vue'

import usePageTable from '@/hooks/usePageTable'
import {
  editComprehensiveScore,
  getComprehensiveScoreList,
} from '@/api/scholarship'
import type { ComprehensiveScore } from '@/types/scholarship'
import { useDict } from '@/utils/dict'
import useUserStore from '@/store/modules/user'
import { download } from '@/utils/request'

export default defineComponent({
  setup() {
    const { sys_user_sex, sys_yes_no } = useDict('sys_user_sex', 'sys_yes_no')
    const router = useRouter()
    const open = ref(false)
    const form = ref<{ isPass?: string; reason?: string }>({ isPass: '', reason: '' })
    const row = ref<ComprehensiveScore>()
    const currentUser = useUserStore()

    const handleView = (id: string | number) => {
      router.push({ path: `/scholarship/comprehensiveScore/audits/detail/${id}` })
    }

    const handleAudit = (data: ComprehensiveScore) => {
      open.value = true
      row.value = data
    }

    /** 列表逻辑 */
    const {
      Table,
      handleSearch,
      QueryForm,
    } = usePageTable<ComprehensiveScore>(
      {
        fields: [],
        initValues: {
          deptId: currentUser.dept?.deptId.toString(),
          pageSize: 10,
          pageNum: 1,
        },
        getList: getComprehensiveScoreList,
      },
      [
        {
          key: 'studentName',
          title: '学生姓名',
        },
        {
          key: 'sex',
          title: '性别',
          render: row =>
            <><DictTag value={row.sex} options={sys_user_sex.value} type="text" /></>,
        },
        {
          key: 'year',
          title: '年份',
        },
        {
          key: 'totalScore',
          title: '所得分数',
        },
        {
          key: 'isPass',
          title: '是否审核通过',
          render: row =>
            <><DictTag value={row.isPass} options={sys_yes_no.value} type="tag" /></>,
        },
        {
          key: 'operate',
          title: '操作',
          render: row => (
            <>
              <ElButton link type="primary" icon="View" onClick={() => handleView(row.id)}>查看详情</ElButton>
              <ElButton link type="primary" icon="Edit" onClick={() => handleAudit(row)}>审核</ElButton>
            </>
          ),
        },
      ],
    )
    void handleSearch()

    const submit = async () => {
      if (row.value) {
        await editComprehensiveScore({
          ...row.value,
          isPass: form.value.isPass,
          reason: form.value.isPass === 'N' ? form.value.reason : '',
        })
        ElMessage.success('操作成功')
        open.value = false
        void handleSearch()
        return
      }
      ElMessage.success('操作失败')
    }

    const handleExport = () => {
      currentUser.dept && void download(
        `/system/comprehensiveScore/export?deptId=${currentUser.dept.deptId}`,
        { deptId: currentUser.dept.deptId },
        `综测_${new Date().getTime()}.xlsx`,
        {
          headers: {
            'Content-Type': 'application/json',
          },
        },
      )
    }

    return () => (
      <div class="p-2 md:p-4 h-full">
        <QueryForm />
        <ElRow gutter={10} class="mb-4">
          <ElCol span={1.5}>
            <ElButton
              type="warning"
              plain
              icon="Download"
              onClick={handleExport}
            >
              导出
            </ElButton>
          </ElCol>
        </ElRow>
        <Table />

        <ElDialog v-model={open.value} title="审核" width="500px" append-to-body>
          {{
            default: () => (
              <ElForm>
                <ElFormItem label="是否通过" required>
                  <ElSelect v-model={form.value.isPass}>
                    {
                      sys_yes_no.value.map(item => <ElOption label={item.label} value={item.value} key={item.value} />)
                    }
                  </ElSelect>
                </ElFormItem>
                {
                  form.value.isPass === 'N'
                  && (
                    <ElFormItem label="拒绝原因" required>
                      <ElInput type="textarea" v-model={form.value.reason} />
                    </ElFormItem>
                  )
                }
              </ElForm>
            ),
            footer: () => (
              <>
                <ElButton type="primary" onClick={submit}>
                  确 定
                </ElButton>
                <ElButton onClick={() => open.value = false}>
                  取 消
                </ElButton>
              </>
            ),
          }}
        </ElDialog>
      </div>
    )
  },
})
